package com.tocea.formation.tpLibraryEjb.eao;

import java.util.List;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import com.tocea.formation.tpLibraryEjb.entities.Author;

@Stateless
@LocalBean
public class AuthorEAO{

	@PersistenceContext
	private EntityManager em;
	
	
	public List<Author> findAuthorByName(String s) {
        Query q = em.createQuery("select aut from Author aut where firstname like '%"+s+"%' or lastname like '%"+s+"%' ");
        @SuppressWarnings("unchecked")
		List<Author> results = (List<Author>) q.getResultList();
        return results;
	}
	
	public Author getAuthor(String _firstname, String _lastname){
	/*	String selectQuery = "select auth from Author aut where firstname like '?1' and lastname like '?2' ";
				selectQuery.setParameter(1, _firstname);
				selectQuery.setParameter(2, _lastname);
		*/ 
		Query q = em.createQuery("select aut from Author aut where firstname like ?1 '"+_firstname+"' or lastname like '"+_lastname+"' ");
       
        return (Author) q.getSingleResult();
	}

	public void addAuthor(String _firstname, String _lastname, Integer age) {
		Author a  = new Author();
		a.setAge(age);
		a.setFirstname(_firstname);
		a.setLastname(_lastname);
		
		em.persist(a);		
	}

	public Integer updateAuthor(Integer id, String _firstname, String _lastname,Integer age) {
		Query q = em.createQuery("Update Author set age = "+age+", firstname = '"+_firstname+"', lastname = '"+_lastname+"' where id = "+id+" ");
        return q.executeUpdate();
	}

	public Integer deleteAuthor(String _firstname, String _lastname){
		Query q = em.createQuery("delete from Author where UPPER(firstname) like '"+_firstname.toUpperCase()+"' and UPPER(lastname) like '"+_lastname.toUpperCase()+"' ");
        return q.executeUpdate();
	}

	public List<Author> getAll() {
		Query q = em.createQuery("from author a");
		@SuppressWarnings("unchecked")
		List<Author> authors = q.getResultList();
		return authors;
	}
	
}
